package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"yh/models"
)

type YhController struct {
	beego.Controller
}

func (c *YhController) List() {
	name := c.GetString("name")
	var yh []models.Yh
	models.DB.Debug().Where("name =?", "%"+name+"%").Find(&yh)
	c.Data["json"] = Res{
		Code: 200,
		Data: yh,
		Msg:  "展示成功",
	}
	c.ServeJSON()
	return
}
func (c *YhController) Update() {
	id, _ := c.GetInt("id")
	name := c.GetString("name")
	price := c.GetString("price")
	num, _ := c.GetInt("num")
	status := c.GetString("status")
	author := c.GetString("author")
	yh := models.Yh{
		Name:   name,
		Price:  price,
		Num:    num,
		Status: status,
		Author: author,
	}
	models.DB.Debug().Where("id=?", id).Updates(&yh)
	c.Data["json"] = Res{
		Code: 200,
		Data: nil,
		Msg:  "修改成功",
	}
	c.ServeJSON()
	return
}
func (c *YhController) Del() {
	id, _ := c.GetInt("id")
	var yh models.Yh
	models.DB.Debug().Where("id=?", id).Delete(&yh)
	c.Data["json"] = Res{
		Code: 200,
		Data: nil,
		Msg:  "删除成功",
	}
	c.ServeJSON()
	return
}
func (c *YhController) Add() {
	name := c.GetString("name")
	price := c.GetString("price")
	num, _ := c.GetInt("num")
	status := c.GetString("status")
	author := c.GetString("author")
	if name == "" || price == "" || num == 0 {
		c.Data["json"] = Res{
			Code: 500,
			Data: nil,
			Msg:  "参数不能为空",
		}
		c.ServeJSON()
		return
	}
	yh := models.Yh{
		Name:   name,
		Price:  price,
		Num:    num,
		Status: status,
		Author: author,
	}
	models.DB.Debug().Create(&yh)
	c.Data["json"] = Res{
		Code: 200,
		Data: nil,
		Msg:  "添加成功",
	}
	c.ServeJSON()
	return
}
